package org.example.likou150.circularList;

import java.util.ArrayList;

public class ReverseBetween {

    public static void main(String[] args) {
        ReverseBetween reverseBetween=new ReverseBetween();
        ListNode node=new ListNode(3);
        ListNode node2=new ListNode(5);
        node.next=node2;
        ListNode node1 = reverseBetween.reverseBetween(node, 1, 2);

    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(right-left <= 1) return head;

        ListNode h = new ListNode(0);
        ListNode preStart = h;
        preStart.next = head;
        int temp=left;
        while (temp > 1){
            preStart = preStart.next;
            temp--;
        }

        ListNode startOne = preStart.next;
        ListNode endTwo = startOne.next;

        for(int i=0; i < right-left; i++){
            startOne.next=endTwo.next;
            endTwo.next=preStart.next;
            preStart.next=endTwo;
            endTwo = startOne.next;
        }

        return h.next;
    }

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
